import React, { useState, useRef, useEffect } from 'react';
import { Alert, KeyboardAvoidingView, Platform, Pressable, StyleSheet, TextInput, View, TouchableWithoutFeedback, Keyboard } from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import { ThemedText } from '@/components/themed-text';
import { ThemedView } from '@/components/themed-view';
import { Fonts } from '@/constants/theme';
import { Link } from 'expo-router';

const API_URL = process.env.EXPO_PUBLIC_API_URL || 'http://localhost:8080';

export default function LoginScreen() {
  const [phone, setPhone] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [remember, setRemember] = useState(true);
  const passwordRef = useRef<TextInput>(null);

  const isValidPhone = (p: string) => /^1[3-9]\d{9}$/.test(p);
  const canSubmit = isValidPhone(phone) && password.length >= 6 && !loading;

  // Web 端：加载已保存的手机号与密码
  useEffect(() => {
    if (Platform.OS === 'web' && typeof window !== 'undefined') {
      try {
        const sp = window.localStorage.getItem('savedPhone') || '';
        const pw = window.localStorage.getItem('savedPassword') || '';
        if (sp) setPhone(sp);
        if (pw) setPassword(pw);
      } catch {}
    }
  }, []);

  const saveWebCreds = () => {
    if (Platform.OS === 'web' && typeof window !== 'undefined') {
      try {
        window.localStorage.setItem('savedPhone', phone);
        window.localStorage.setItem('savedPassword', password);
      } catch {}
    }
  };

  const onLogin = async () => {
    if (!isValidPhone(phone) || !password) {
      Alert.alert('提示', '请输入有效手机号和密码');
      return;
    }
    try {
      setLoading(true);
      const res = await fetch(`${API_URL}/api/login`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: phone, password }),
      });
      const data = await res.json();
      if (data.code === 0) {
        if (remember) saveWebCreds();
        Alert.alert('登录成功', '欢迎进入语音房');
        // TODO: 保存 token 并跳转到主界面
      } else {
        Alert.alert('登录失败', data.msg || '请检查手机号或密码');
      }
    } catch (e) {
      Alert.alert('错误', '网络请求失败');
    } finally {
      setLoading(false);
    }
  };

  const onQuickLogin = async () => {
    // Web 端：使用本地存储的一键登录；原生端：直接使用当前输入进行一键登录
    if (Platform.OS === 'web' && typeof window !== 'undefined') {
      const sp = window.localStorage.getItem('savedPhone') || '';
      const pw = window.localStorage.getItem('savedPassword') || '';
      if (!isValidPhone(sp) || pw.length < 6) {
        Alert.alert('提示', '请先用手机号+密码登录并选择记住账号');
        return;
      }
      setPhone(sp);
      setPassword(pw);
    }
    onLogin();
  };

  return (
    <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined} style={{ flex: 1 }}>
      <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
        <LinearGradient
          colors={["#ffe4ec", "#ffc2d8", "#ff99c8"]}
          start={{ x: 0, y: 0 }}
          end={{ x: 1, y: 1 }}
          style={styles.gradient}
        >
          <View style={styles.container}>
            <ThemedView style={styles.card}>
              <ThemedText type="title" style={styles.title}>语音房</ThemedText>

              <Pressable onPress={onQuickLogin} style={({ pressed }) => [styles.button, pressed && styles.buttonPressed]} disabled={loading}>
                <LinearGradient
                  colors={["#ff6fa8", "#ff85b8"]}
                  start={{ x: 0, y: 0 }}
                  end={{ x: 1, y: 1 }}
                  style={styles.buttonGradient}
                >
                  <ThemedText style={styles.buttonText}>{loading ? '处理中...' : '本机号一键登录'}</ThemedText>
                </LinearGradient>
              </Pressable>

              <View style={styles.formItem}>
                <TextInput
                  value={phone}
                  onChangeText={(t) => setPhone(t.replace(/\D/g, ''))}
                  placeholder="手机号"
                  placeholderTextColor="#b58597"
                  autoCapitalize="none"
                  keyboardType={Platform.OS === 'ios' ? 'number-pad' : 'phone-pad'}
                  autoComplete="tel"
                  textContentType="telephoneNumber"
                  returnKeyType="next"
                  maxLength={11}
                  onSubmitEditing={() => passwordRef.current?.focus()}
                  style={styles.input}
                />
              </View>

              <View style={styles.formItem}>
                <TextInput
                  ref={passwordRef}
                  value={password}
                  onChangeText={setPassword}
                  placeholder="密码"
                  placeholderTextColor="#b58597"
                  secureTextEntry
                  style={styles.input}
                />
              </View>

              <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
                <Pressable onPress={() => setRemember(!remember)} style={({ pressed }) => [{ paddingVertical: 6, paddingHorizontal: 8, borderRadius: 6 }, pressed && { opacity: 0.9 }]}>
                  <ThemedText style={{ color: '#a24768' }}>{remember ? '✓ 记住账号（Web）' : '记住账号（Web）'}</ThemedText>
                </Pressable>
                {/* 可扩展：忘记密码、帮助链接 */}
              </View>

              <Pressable onPress={onLogin} style={({ pressed }) => [styles.button, pressed && styles.buttonPressed]} disabled={!canSubmit}>
                <LinearGradient
                  colors={["#ff6fa8", "#ff85b8"]}
                  start={{ x: 0, y: 0 }}
                  end={{ x: 1, y: 1 }}
                  style={styles.buttonGradient}
                >
                  <ThemedText style={styles.buttonText}>{loading ? '登录中...' : '登录'}</ThemedText>
                </LinearGradient>
              </Pressable>

              {/* 已移除注册入口 */}
            </ThemedView>
          </View>
        </LinearGradient>
      </TouchableWithoutFeedback>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  gradient: {
    flex: 1,
  },
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    padding: 24,
  },
  card: {
    width: '100%',
    maxWidth: 420,
    borderRadius: 16,
    padding: 20,
    backgroundColor: '#ffffffcc',
    ...Platform.select({ web: { backdropFilter: 'blur(6px)' } }),
  },
  title: {
    textAlign: 'center',
    marginBottom: 16,
    fontFamily: Fonts.rounded,
    color: '#d94c7f',
  },
  formItem: {
    marginBottom: 12,
  },
  label: {
    marginBottom: 8,
    fontFamily: Fonts.sans,
    color: '#a24768',
  },
  input: {
    borderWidth: 1,
    borderColor: '#f1bfd0',
    borderRadius: 10,
    paddingHorizontal: 12,
    paddingVertical: 12,
    fontSize: 16,
    backgroundColor: '#fff',
    minHeight: 44,
  },
  button: {
    marginTop: 8,
    borderRadius: 10,
    overflow: 'hidden',
  },
  buttonGradient: {
    height: 48,
    alignItems: 'center',
    justifyContent: 'center',
  },
  buttonPressed: {
    opacity: 0.9,
  },
  buttonText: {
    color: '#fff',
    fontWeight: '700',
    fontSize: 16,
  },
  footer: {
    marginTop: 12,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: 6,
  },
  footerText: {
    color: '#a24768',
  },
  linkText: {
    color: '#d94c7f',
    textDecorationLine: 'underline',
    fontWeight: '600',
  },
});